package cn.com.haopy.dataes.db.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 向指定 URL 发送POST方法的请求
 *
 * @return 远程资源的响应结果
 */
@Slf4j
public class HttpUtils {
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param params 请求的参数集合
     * @return 远程资源的响应结果
     */
    @SuppressWarnings("unused")
    public static String sendPost(String url, Map<String, String> params) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // POST方法
            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            if (params != null) {
                StringBuilder param = new StringBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if (param.length() > 0) {
                        param.append("&");
                    }
                    param.append(entry.getKey());
                    param.append("=");
                    param.append(entry.getValue());

                }

                out.write(param.toString());
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error(ex.getMessage(), ex);
            }
        }
        return result.toString();
    }

    /**
     * 向指定URL发送POST方法请求
     * @param url 发送请求的URL
     * @param params
     * @return
     */
    public static JSONObject postJSON(String url, Map<String, String> header, Map<String, Object> params) {
        log.debug("访问地址：" + url);
        log.debug("header：" + JSONObject.toJSONString(header));
        log.debug("params:" + JSONObject.toJSONString(params));

        return postData(url, header, params, "json");
    }

    public static JSONObject postFormData(String url, Map<String, String> header, Map<String, Object> params) {
        return postData(url, header, params, "form");
    }

    private static JSONObject postData(String url, Map<String, String> header, Map<String, Object> params, String postType) {
        try {
            String res = doPost(url, header, params, postType);

            if (res == null) {
                throw new Exception("访问异常");
            }

            return JSONObject.parseObject(res);
        } catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }

        return null;
    }

    private static String doPost(String url, Map<String, String> header, Map<String, Object> param, String postType)
            throws IOException, NoSuchAlgorithmException, KeyManagementException {
        System.out.println(url);
        CloseableHttpClient httpClient = getHttpClient(url.startsWith("https://"));

        CloseableHttpResponse response = null;
        String resultString = "";

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(300000)
                .setConnectTimeout(300000)
                .setConnectionRequestTimeout(300000)
                .build();

        // 创建Http Post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        if (header != null) {
            for (Map.Entry<String, String> e: header.entrySet()) {
                httpPost.setHeader(e.getKey(), e.getValue());
            }
        }

        HttpEntity entity = getHttpEntity(param, postType);

        if (entity != null) httpPost.setEntity(entity);

        //获取返回值
        CloseableHttpResponse res = httpClient.execute(httpPost);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            resultString = EntityUtils.toString(res.getEntity());// 返回json格式：
            log.info(url + " POST请求返回的数据是：" + resultString);
        }

        if (response != null) {
            response.close();
        }

        if (httpClient != null) {
            httpClient.close();
        }

        return resultString;
    }

    private static CloseableHttpClient getHttpClient(boolean isSSL) throws NoSuchAlgorithmException, KeyManagementException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        if (isSSL) {
            // SSL访问
            SSLContext context = SSLContext.getInstance("SSL");

            X509TrustManager manager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    // TODO Auto-generated method stub
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    // TODO Auto-generated method stub

                }
            };

            context.init(null, new TrustManager[] { manager }, null);

            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context,
                    NoopHostnameVerifier.INSTANCE);

            httpClient = HttpClients.custom().setSSLContext(context).build();
        }

        return httpClient;
    }

    private static HttpEntity getHttpEntity(Map<String, Object> params, String postType) throws UnsupportedEncodingException {
        if (params == null) return null;

        if ("form".equals(postType)) {
            List<NameValuePair> paramList = new ArrayList<>();
            for (String key : params.keySet()) {
                paramList.add(new BasicNameValuePair(key, params.get(key).toString()));
            }

            // 模拟表单
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");

            return entity;
        }

        if ("json".equals(postType)) {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(params), "utf-8");
            entity.setContentType("application/json");
            entity.setContentEncoding("utf-8");

            return entity;
        }

        return null;
    }
}
